package com.ms.p2p.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.utils.*;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.account.Account;
import com.ms.p2p.entity.account.AccountBank;
import com.ms.p2p.entity.account.AccountRecharge;
import com.ms.p2p.entity.account.YuEbao;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.entity.member.Email;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.entity.system.PayMethod;
import com.ms.p2p.provider.*;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping({ "/member" })
public class MemberController extends BaseController {

	@Reference
	private MemberAccountProvider account_Service;
	@Reference
	private MemberAccountBankProvider bankService;
	@Reference
	private CertiFiCationProvider certificationProvider;
	@Reference
	private MailAuthProvider mailAuthProvider;
	@Reference
	private LoanDueInProvider loanDueInProvider;
	@Reference
	private MemberAccountRechargeProvider rechargeService;
	@Reference
	private MemberProvider memberProvider;

	@Reference
	private PayMethodProvider payMethodProvider;
	@Reference
	private SettingProvider settingProvider;

	@Reference
	private YeahpaysProvider yeahpaysProvider;
	@Reference
	private SendProvider smsService;
	@Reference
	private MemberAccountRecordProvider logService;



	@Reference
	RedPacketProvider redPacketProvider;

	@RequestMapping({ "/account/redpacket/list" })
	public String list(HttpServletRequest request) {
		Member user =getCurrentUser();
		PageBean page = new PageBean();
		page.setPageSize(999);
		request.setAttribute("evclist", redPacketProvider.findPager(page,null,user.getId(),null));
		return "customer/member/account/redpacket/list";

	}

	/**
	 * 我的账户
	 */
	@RequestMapping({""})
	public String index(Model model) {
		Member user = getCurrentUser();


		Auth realName = certificationProvider.findByUserId(user.getId());
		Email email = mailAuthProvider.findByUserId(user.getId());
		Account account = account_Service.findByUserId(user.getId());
		String income = loanDueInProvider.getIncome(user.getId(), 1);
		YuEbao yuEbao = yeahpaysProvider.findByUserId(user.getId());

		List<Map<String, Object>> logs =
				logService.findPager(user.getId() + "", null, null, null, null, 0, 10);
		String yield = settingProvider.findValueByCode("yuebao_yield");
		model.addAttribute("yield", yield);
		model.addAttribute("yuEbao", yuEbao);
		model.addAttribute("income", income);
		model.addAttribute("yuebao", yeahpaysProvider.findByUserId(user.getId()));
		model.addAttribute("logs", logs);
		model.addAttribute("account", account);
		model.addAttribute("email", email);
//		model.addAttribute("mobile", mobile);
		model.addAttribute("realName", realName);
		return "customer/member/index";

	}

	@RequestMapping({"/selectbankStatus"})
	@ResponseBody
	public int selectbankStatus(HttpServletRequest request, HttpSession session) {
		Member user = getCurrentUser();
		AccountBank bankCard = bankService.findByUserId(user.getId());
		request.setAttribute("bankCard", bankCard);
		if (bankCard == null) {
			// 如果还未绑定银行卡，跳转到银行卡绑定页面
			return 0;
		} else {
			return 1;
		}
	}

	/**
	 * @param request
	 * @param session
	 * @return String 返回类型
	 * @Title: toPersonalAuth
	 * @Description: 到实名认证页面
	 */
	@RequestMapping({"/auth"})
	public String toPersonalAuth(HttpServletRequest request, HttpSession session) {
		Member user = getCurrentUser();
		if (user != null) {
			Auth realName = certificationProvider.findByUserId(user.getId());
			request.setAttribute("realName", realName);
		}
		return "/customer/member/ucenter/auth/real";
	}


	@RequestMapping(value = {"/kefusubmit"}, produces = {"application/text;charset=UTF-8"})
	@ResponseBody
	public String kefusubmit(HttpServletRequest request, HttpSession session) {
		Member principal = (Member) AppContext.getSessionAttr("loginUser");
		String kefu_id = request.getParameter("kefu_id");
		memberProvider.updateKefuByid(principal.getId(), kefu_id);
		return "成功";

	}

	/**
	 * 线下充值
	 */

	@Validations(
			requiredStrings = {
					@RequiredStringValidator(fieldName = "tradeNo", message = "汇款单号不能为空"),
					@RequiredStringValidator(fieldName = "money", message = "汇款金额不能为空"),
					@RequiredStringValidator(fieldName = "payMethod", message = "汇款账号不能为空"),
					@RequiredStringValidator(fieldName = "captcha", message = "验证码不能为空")
			}
	)
	@RequestMapping(value = {"/account/recharge_offline"})
	@ResponseBody
	public Message recharge_offline(Integer payMethod, Double money, String tradeNo,String captcha) {

		//验证码校验
		String sessionCaptcha = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(sessionCaptcha) || StringUtils.isBlank(captcha) || !sessionCaptcha.toLowerCase().equals(captcha.toLowerCase())) {
			return Message.error("图形验证码不能为空");
		}
		Member user = getCurrentUser();
		String retmsg = certificationProvider.getCertiStatus(user.getId());
		if(StringUtils.isNotBlank(retmsg)){
			return Message.error(retmsg);
		}
		// 支付方式
		PayMethod paymentMethod = payMethodProvider.findById(payMethod+"");
		if(paymentMethod == null){
			return Message.error("支付方式不存在，请联系客服！");
		}
		// 充值手续费率
		BigDecimal recharge_fee = new BigDecimal(settingProvider.findValueByCode("recharge_fee"));
		BigDecimal amount = new BigDecimal(money);
		BigDecimal fee = amount.multiply(recharge_fee);
		AccountRecharge recharge = new AccountRecharge();
		recharge.setUser_id(user.getId());
		recharge.setAddtime(MsDateUtils.getTime());
		recharge.setAddip(AppContext.getRemoteIp());
		recharge.setStatus(0);
		recharge.setMoney(amount);
		recharge.setFee(fee);
		recharge.setAmount(amount.subtract(fee));
		recharge.setType(0);
		recharge.setPayment(payMethod);
		recharge.setTrade_no(tradeNo);
		recharge.setRemark(paymentMethod.getName() + "-" + paymentMethod.getDescription());
		rechargeService.insert(recharge);
		AppContext.removeAttribute(Constants.CAPTCHA_SESSION_KEY);
		return successMessage;
	}

	@RequestMapping({ "/ucenter/pwd/{type}" })
	public String pwd(HttpServletRequest request, @PathVariable String type)
			throws IllegalAccessException, InvocationTargetException,
			IntrospectionException, IOException {
		request.setAttribute("type", type);
		return "customer/member/ucenter/safe/pwd";
	}




	/**
	 * 找回密码 第一步填写手机号验证码
	 */
	@RequestMapping(value = "/forget", method = RequestMethod.GET)
	public String toForget(Model model) {
		Member user = getCurrentUser();
		String mobile = user.getMember_phone();
		String token = CommonUtil.getUUID();
		model.addAttribute("mobile", mobile);
		model.addAttribute("token", token);
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token, mobile);
		return "/customer/member/ucenter/forget/step2";
	}

	/**
	 *	找回密码第二步--发送短信
	 */
	@RequestMapping(value = "/sms/forget", method = RequestMethod.POST)
	@ResponseBody
	public String SendSmsForget(String token, String captcha,
								HttpServletResponse response) throws IOException, TemplateException {

		if(StringUtils.isBlank(token)){
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		if(StringUtils.isBlank(captcha)){
			return ResponseUtils.renderJSON(Message.error("图形验证码不能为空！"), response);
		}

		String mobile = (String) AppContext.getSessionAttr(token);
		if (StringUtils.isBlank(mobile)) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		//发送校验
		String msg = isValidSms(mobile, captcha, true);
		if(StringUtils.isNotBlank(msg)){
			return ResponseUtils.renderJSON(Message.error(msg), response);
		}

		Member user = memberProvider.findByMobilePhone(mobile);
		if (user == null) {
			return ResponseUtils.renderJSON(Message.error("该手机绑定用户不存在"), response);
		}
		FreeMarkerConfigurer freeMarkerConfigurer = SpringContextHolder.getBean("freeMarkerConfigurer");
		//
		//
		String mobileCode = CommonUtil.getRandomNum(6);
		String nickname = settingProvider.findByCode("email_from_name")
				.getText();
		String templatePath = Constants.TEMPLATE_SMS_BIND;
		Configuration configuration = freeMarkerConfigurer.getConfiguration();
		Template template = configuration.getTemplate(templatePath, "utf-8");
		HashMap map = new HashMap();
		map.put("code",mobileCode);
		String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
		// 发送短信
		Message message = smsService.sendSMS(mobile,"【"+nickname+"】"+content, "注册", 0);

		if (Message.Type.success.equals(message.getType())) {
			AppContext.setSessionAttr(Constants.COMMON_MOBILE_CODE_SESSION_KEY, mobileCode+"_"+System.currentTimeMillis());
			AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY + mobile, user.getId()+"");
		}

		return ResponseUtils.renderJSON(message, response);
	}

	/**
	 *	找回密码第二步--验证短信验证码
	 */
	@RequestMapping(value = "/forget2", method = RequestMethod.POST)
	@ResponseBody
	public String forget(String token, String captcha, String code, HttpServletResponse response) {
		//验证码校验
		String sessionCaptcha = (String) AppContext.getSessionAttr(Constants.CAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(sessionCaptcha) || StringUtils.isBlank(captcha) || !sessionCaptcha.toLowerCase().equals(captcha.toLowerCase())) {
			return ResponseUtils.renderJSON(Message.error("图形验证码不能为空"), response);
		}

		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || StringUtils.isBlank(token) || !token.equals(sessionToken)) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		//获取手机号码
		String mobile = (String) AppContext.getSessionAttr(token);
		if(StringUtils.isBlank(mobile)){
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		//短信验证码校验
		String mobileCode = (String) AppContext.getSessionAttr(Constants.COMMON_MOBILE_CODE_SESSION_KEY);
		String userid = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY+mobile);
		if(StringUtils.isBlank(mobileCode) && StringUtils.isBlank(userid)){
			return ResponseUtils.renderJSON(Message.error("请发送短信验证码！"), response);
		}

		if(StringUtils.isBlank(userid)){
			return ResponseUtils.renderJSON(Message.error("请刷新页面，重新提交！"), response);
		}

		if (StringUtils.isBlank(mobileCode) || StringUtils.isBlank(code) || !mobileCode.contains("_")) {
			return ResponseUtils.renderJSON(Message.error("短信验证码错误或已过期失效！"), response);
		}

		String[] codes = StringUtils.split(mobileCode, "_");
		if(codes == null || codes.length != 2 || System.currentTimeMillis() - Long.valueOf(codes[1]) > 1000*60*10){
			return ResponseUtils.renderJSON(Message.error("短信验证码错误或已过期失效！"), response);
		}
		//
		token = CommonUtil.getUUID();
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token+"_USERID", userid);
		//
		AppContext.removeAttribute(Constants.FORGET_PASS_SESSION_KEY + mobile);
		AppContext.removeAttribute(Constants.COMMON_MOBILE_CODE_SESSION_KEY);
		AppContext.removeAttribute(token);

		return ResponseUtils.renderJSON(Message.success(token), response);
	}


	@RequestMapping(value = "/forget3", method = RequestMethod.GET)
	public String forget3(String token, Model model){
		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || !token.equals(sessionToken)) {
			return "redirect:/forget";
		}
		String userId = (String) AppContext.getSessionAttr(sessionToken+"_USERID");
		if (StringUtils.isBlank(userId)) {
			return "redirect:/forget";
		}
		model.addAttribute("token", token);
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY, token);
		AppContext.setSessionAttr(token + "_USERID", userId);
		return "/customer/member/ucenter/forget/step3";
	}

	/**
	 * 重置密码
	 */
	@RequestMapping(value = "/forget3", method = RequestMethod.POST)
	@ResponseBody
	public String forgetResetPwd(String token, String pwd, HttpServletResponse response){

		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY);
		if (StringUtils.isBlank(sessionToken) || StringUtils.isBlank(token) || !sessionToken.toLowerCase().equals(token.toLowerCase())) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面,重新提交！"), response);
		}

		String userId = (String) AppContext.getSessionAttr(token+"_USERID");
		if (StringUtils.isBlank(userId)) {
			return ResponseUtils.renderJSON(Message.error("请刷新页面,重新提交！"), response);
		}

		Member user = memberProvider.findById(Integer.valueOf(userId));
		if (user == null) {
			return ResponseUtils.renderJSON(Message.error("该手机绑定用户不存在"), response);
		}

		user.setPayment_password(DigestUtils.md5Hex(pwd));
		memberProvider.update(user);

		token = CommonUtil.getUUID();
		AppContext.setSessionAttr(Constants.FORGET_PASS_SESSION_KEY + "_SUCCESS", token);
		//
		AppContext.removeAttribute(Constants.FORGET_PASS_SESSION_KEY);
		AppContext.removeAttribute(token + "_USERID");

		return ResponseUtils.renderJSON(Message.success(token), response);
	}

	@RequestMapping(value = "/forget4", method = RequestMethod.GET)
	public String forget4(String token){
		String sessionToken = (String) AppContext.getSessionAttr(Constants.FORGET_PASS_SESSION_KEY+"_SUCCESS");
		if (StringUtils.isBlank(sessionToken) || !token.equals(sessionToken)) {
			return "redirect:/forget";
		}
		AppContext.removeAttribute(Constants.FORGET_PASS_SESSION_KEY + "_SUCCESS");
		return "/customer/member/ucenter/forget/step4";
	}

}
